package persistence.dao;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import persistence.db.DataSet;
import persistence.db.DatabaseConnector;
import persistence.model.AbstractModel;
import persistence.model.Service;

public class ServiceDAO extends AbstractDAO{
	
	private Service service;
	
	/**
	 * Constructeur d'un service DAO
	 */
	public ServiceDAO() {
		setTableName("SERVICE");
	}

	/**
	 * Constructeur d'un service DAO
	 * @param serv service associé
	 */
	public ServiceDAO(Service serv) {
		this();
		service = serv;
		setId(serv.getId());
	}
	
	public DataSet all() {
		return new DataSet(this);
	}

	public AbstractModel makeModel(ResultSet rset) {
		
		try {
			setId(rset.getInt("ID_SERVICE"));
			System.out.println("DAO: "+this.getId());
			return new Service(this.getId(),
					rset.getInt("nbPeriodes"),
					rset.getInt("fk_see"), //TODO renommer en fk_service_see apres MaJ BD
					rset.getInt("fk_service_type_heure"),
					rset.getInt("fk_service_enseignant"),
					rset.getInt("fk_service_groupe"));
		} catch (SQLException e) {
			System.out.println("makeModel error");
			e.printStackTrace();
		}
		return null;
	}

	public void save() {
		String query;
		ResultSet result;
		query = "INSERT INTO " + getTableName() +
			" VALUES ( S_PK_" + getTableName() + ".nextval, " +
			service.getNbPeriodes() + ", " +
			service.getFk_service_see() + ", "+
			service.getFk_service_type_heure() + ", " +
			service.getFk_service_enseignant() + ", " +
			service.getFk_service_groupe() + ")";
		/* Execute la requete */
		result = DatabaseConnector.getInstance().execute(query);
		setId(this.getId()); /* Mise a jour de l'identifiant */
	}

	public void save(int id) {
		String query;
		ResultSet result;
		query = "UPDATE " + getTableName() +
			" SET nbPeriodes = " + service.getNbPeriodes() +
			", fk_see = " + service.getFk_service_see() +
			", fk_service_type_heure = "+ service.getFk_service_type_heure() +
			", fk_service_enseignant = " + service.getFk_service_enseignant() +
			", fk_service_groupe = " + service.getFk_service_groupe() +
			" WHERE ID_"+ getTableName() + " = "+ id;
		/* Execute la requete */
		result = DatabaseConnector.getInstance().execute(query);
	}
}
